import { Injectable } from '@nestjs/common';
import { Response } from 'express';
import { ResultData } from 'src/common/utils/result';
import { ExportTable } from 'src/common/utils/export';
import { CreateLoginlogDto, ListLoginlogDto } from './dto/index';
import { PrismaService } from '@/module/common/prisma/prisma.service';
import { pickEquals, pickLike } from '@/common/utils/prisma';
import { PrismaConst } from '@/common/constant/prisma.constant';

@Injectable()
export class LoginlogService {
    constructor(
        private readonly prisma: PrismaService
    ) { }

    /**
     * 创建用户登录日志
     * @param createLoginlogDto
     * @returns
     */
    async create(createLoginlogDto: CreateLoginlogDto) {
        return await this.prisma.logininfor.create({ data: pickEquals(createLoginlogDto, PrismaConst.logininfor) });
    }

    /**
     * 日志列表-分页
     * @param query
     * @returns
     */
    async findAll(query: ListLoginlogDto) {
        console.log(JSON.parse(JSON.stringify(query)), 'query');

        let where: any = {
            delFlag: '0',
            ...pickEquals(query, ['status']),
            ...pickLike(query, ['ipaddr', 'userName']),
        };
        if (query?.beginTime && query?.endTime) {
            where.loginTime = {
                gte: new Date(query.beginTime),
                lte: new Date(query.endTime),
            };
        }
        const orderBy = query.orderByColumn && query.isAsc ? {
            [query.orderByColumn]: query.isAsc === 'ascending' ? 'asc' : 'desc',
        } : undefined;
        const skip = query.pageSize && query.pageNum ? query.pageSize * (query.pageNum - 1) : undefined;
        const take = query.pageSize ? +query.pageSize : undefined;
        const [list, total] = await Promise.all([
            this.prisma.logininfor.findMany({
                where,
                orderBy,
                skip,
                take,
            }),
            this.prisma.logininfor.count({ where }),
        ]);
        return ResultData.ok({
            list,
            total,
        });
    }

    /**
     * 删除日志
     * @returns
     */
    async remove(ids: string[]) {
        const data = await this.prisma.logininfor.updateMany({
            where: {
                infoId: {
                    in: ids.map(id => +id),
                },
            },
            data: {
                delFlag: '1', // 更新 `delFlag` 字段为 '1'
            },
        });
        return ResultData.ok(data);
    }

    /**
     * 删除全部日志
     * @returns
     */
    async removeAll() {

        await this.prisma.logininfor.updateMany({
            where: {
                infoId: {
                    not: undefined, // 使用 `isNot` 来匹配 `infoId` 不为空的记录
                }
            },
            data: {
                delFlag: '1', // 更新 `delFlag` 字段为 '1'
            },
        });
        return ResultData.ok();
    }

    /**
     * 导出登录日志数据为xlsx
     * @param res
     */
    async export(res: Response, body: ListLoginlogDto) {
        delete body.pageNum;
        delete body.pageSize;
        const list = await this.findAll(body);
        const options = {
            sheetName: '登录日志',
            data: list.data.list,
            header: [
                { title: '序号', dataIndex: 'infoId' },
                { title: '用户账号', dataIndex: 'userName' },
                { title: '登录状态', dataIndex: 'status' },
                { title: '登录地址', dataIndex: 'ipaddr' },
                { title: '登录地点', dataIndex: 'loginLocation' },
                { title: '浏览器', dataIndex: 'browser' },
                { title: '操作系统', dataIndex: 'os' },
                { title: '提示消息', dataIndex: 'msg' },
                { title: '访问时间', dataIndex: 'loginTime' },
            ],
            dictMap: {
                status: {
                    '0': '成功',
                    '1': '失败',
                },
            },
        };
        ExportTable(options, res);
    }
}
